package top.codestudy.btpair;

import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;

import top.codestudy.btpair.util.BTManager;

import static top.codestudy.btpair.util.BTManager.bluetoothAdapter;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    // Create a BroadcastReceiver for ACTION_FOUND.
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Discovery has found a device. Get the BluetoothDevice
                // object and its info from the Intent.
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address

            }
            if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
                int scan_mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, -1);
                int old_scan_mode = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE, -1);
                Log.i(TAG, "onReceive: EXTRA_SCAN_MODE ==> " + scan_mode + " ; EXTRA_PREVIOUS_SCAN_MODE ==> " + old_scan_mode);
            }
        }
    };
    //honorPad
    String mac = "F0:C8:50:A0:7F:CB";
    String uuid = "a6453f8a-4475-49a6-b625-dd35bd674eca";
    String AUDIOSYNQ_MAC = "00:23:01:10:35:78";
    BluetoothA2dp bluetoothA2dp;
    private BluetoothProfile.ServiceListener profileListener = new BluetoothProfile.ServiceListener() {
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            if (profile == BluetoothProfile.A2DP) {
                Log.i(TAG, "onServiceConnected: BluetoothProfile.A2DP");
                bluetoothA2dp = (BluetoothA2dp) proxy;

            }
        }

        public void onServiceDisconnected(int profile) {
            if (profile == BluetoothProfile.A2DP) {
                bluetoothA2dp = null;
            }
        }
    };
    BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(AUDIOSYNQ_MAC);
    BluetoothHeadset bluetoothHeadset;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        registerReceiver(receiver, filter);
//        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3100);
//        startActivityForResult(discoverableIntent,222);
        bluetoothAdapter.startDiscovery();
        //bluetoothHeadset.startVoiceRecognition()
        pair_a2dp();
        findBondDevices();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                boolean bond = remoteDevice.createBond();
                Log.i(TAG, "run: bond = " + bond);
            }
        }, 5000);

        //bluetoothA2dp.getConnectionState()
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult: requestCode ==> " + requestCode + " ; resultCode ==> " + resultCode);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(bluetoothA2dp !=null){
            bluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP,bluetoothA2dp);
        }

        // Don't forget to unregister the ACTION_FOUND receiver.
        unregisterReceiver(receiver);
    }

    public void connect() {
        BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(mac);
        Log.i(TAG, "onCreate: remoteDevice" + remoteDevice);
        try {
            final BluetoothSocket rfcommSocketToServiceRecord = remoteDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.i(TAG, "run: rfcommSocketToServiceRecord.connect();");
                    try {
                        rfcommSocketToServiceRecord.connect();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "客户端连接成功！！", Toast.LENGTH_LONG).show();
                            }
                        });
                    } catch (IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "客户端连接IOException！！", Toast.LENGTH_LONG).show();
                            }
                        });
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void accept() {
        try {
            final BluetoothServerSocket btPair = bluetoothAdapter.listenUsingRfcommWithServiceRecord("BTPair", UUID.fromString(uuid));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.i(TAG, "run:   btPair.accept();");
                    try {
                        btPair.accept();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "服务端连接成功！！", Toast.LENGTH_LONG).show();
                            }
                        });
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void pair_a2dp() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // Establish connection to the proxy.
        bluetoothAdapter.getProfileProxy(MainActivity.this, profileListener, BluetoothProfile.A2DP);
    }

    public void remove_bond(View view) {
        try {
            Method removeBond = remoteDevice.getClass().getDeclaredMethod("removeBond");
            removeBond.invoke(remoteDevice);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public  void disconnect(View view){
        Log.i(TAG,"disconnect");
        if(bluetoothA2dp == null){
            return;
        }
        if(remoteDevice == null){
            return;
        }

        try {
            Method disconnect = bluetoothA2dp.getClass().getDeclaredMethod("disconnect", BluetoothDevice.class);
            disconnect.setAccessible(true);
            disconnect.invoke(bluetoothA2dp,remoteDevice);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            Log.e(TAG,"connect exception:"+e);
            e.printStackTrace();
        }
    }

    public  void connect2(View view){
        Log.i(TAG,"connect");
        if(bluetoothA2dp == null){
            return;
        }
        if(remoteDevice == null){
            return;
        }

        try {
            Method connect = bluetoothA2dp.getClass().getDeclaredMethod("connect", BluetoothDevice.class);
            connect.setAccessible(true);
            connect.invoke(bluetoothA2dp,remoteDevice);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            Log.e(TAG,"connect exception:"+e);
            e.printStackTrace();
        }
    }

    public void findBondDevices() {
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            // There are paired devices. Get the name and address of each paired device.
            for (BluetoothDevice device : pairedDevices) {
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address
                Log.i(TAG, "onReceive: deviceHardwareAddress ==> " + deviceHardwareAddress + "; deviceName ==> " + deviceName);
            }

        }
    }
}